#include "extramethods.h"
#include <iostream>

// using std::string;


string stripWhiteSpaces(string str)
{
    string sep = " \t";
    // strip of leading whitespaces and tabs
    while (str.find_first_of(sep) == 0 ) {
        str = str.substr(1,str.size());
    }
    //detecting empty lines
    if(str.size()!=0)
    {
        // strip of trailing whitespaces and tabs
        while (str.find_last_of(sep) == str.size()-1 ) {
            str = str.substr(0,str.size()-1);
        }
    }
    return str;
}

void whatToModify(char replacing,string replaceWith,string &toModify)
{
    string::size_type loc = 0;
	while(string::npos!=loc)
	{ // checking for the char to be replaced starting from char 1 (not 0)
		loc = toModify.find( replacing, loc+1 );
		if( loc != string::npos){
	    	toModify.replace( loc, 1, replaceWith, 0, replaceWith.size());
		}
	}
	//extra run for checking whether the first one is not the char to be searched
	loc = 0;
	loc = toModify.find( replacing, 0 );
	if( (loc != string::npos) && (loc != toModify.find(replaceWith,0)) ){
    	toModify.replace( loc, 1, replaceWith, 0, replaceWith.size());
	}
}

void whatToModify(string replacing,char replaceWith,string &toModify)
{
	string::size_type loc = 0;
	while(string::npos!=loc)
	{ //checking for the string replacing to be replaced by the char
		loc = toModify.find( replacing, loc +1 );
		if( loc != string::npos){
	    	toModify.replace( loc, replacing.size(), 1 , replaceWith);
		}
	}
	//extra run for checking whether the first chars are not the the string to be searched
	loc = 0;
	loc = toModify.find( replacing, 0 );
	if( loc != string::npos){
    	toModify.replace( loc, replacing.size(), 1 , replaceWith);
	}
}

void changeToDirFromFilelocation(const string filename)
{
    string dir = filename;
    #if defined(_WIN32)
        string slash = "\\";
    #else
        string slash = "/";
    #endif
    uint i = dir.find_last_of( slash, dir.size());
    bool ErrorFlag;
    if(string::npos!=i)
    {
        dir.erase(i);
        ErrorFlag = chdir(dir.c_str());
    }
    if (ErrorFlag)
        std::cerr << "The directory: '"<< dir << "' was not found" << std::endl;
}
